package org.primefaces.model.chart.flow.step;

import java.util.logging.Level;
import java.util.logging.Logger;

import org.primefaces.json.JSONException;
import org.primefaces.json.JSONObject;
import org.primefaces.model.chart.flow.FlowStep;
import org.primefaces.util.ArrayUtils;

public class PictureStep extends FlowStep {

	private final static Logger logger = Logger.getLogger(PictureStep.class
			.getName());

	public static final String TYPE_NAME = "picture";

	// 图片开始的X坐标
	public static final String S_X = "sx";
	// 图片开始的Y坐标
	public static final String S_Y = "sy";
	// 图片取图的宽度
	public static final String S_WIDTH = "sWidth";
	// 图片取图的高度
	public static final String S_HEIGHT = "sHeight";
	// 图片的Src
	public static final String S_IMG_SRC = "imgSrc";
	// 图片的ID
	public static final String S_IMG_ID = "imgId";

	public static final String[] PICTURE_STEP_ATTRIBUTE = ArrayUtils.concat(
			STEP_ATTRIBUTE, new String[] { S_X, S_Y, S_WIDTH, S_HEIGHT,
					S_IMG_SRC, S_IMG_ID });

	@Override
	public String getType() {
		return FlowStep.SYS_FLOW_STEP_TYPE_PREFIX + TYPE_NAME;
	}

	@Override
	public JSONObject toJSON() {
		try {
			// 添加父类属性
			JSONObject jo = super.toJSON();

			if (this.hasAttribute(S_X))
				jo.put(S_X, Integer.valueOf(this.getAttribute(S_X)));

			if (this.hasAttribute(S_Y))
				jo.put(S_Y, Integer.valueOf(this.getAttribute(S_Y)));

			if (this.hasAttribute(S_WIDTH))
				jo.put(S_WIDTH, Integer.valueOf(this.getAttribute(S_WIDTH)));

			if (this.hasAttribute(S_HEIGHT))
				jo.put(S_HEIGHT, Integer.valueOf(this.getAttribute(S_HEIGHT)));

			if (this.hasAttribute(S_IMG_SRC))
				jo.put(S_IMG_SRC, this.getAttribute(S_IMG_SRC));

			if (this.hasAttribute(S_IMG_ID))
				jo.put(S_IMG_ID, this.getAttribute(S_IMG_ID));

			return jo;
		} catch (JSONException e) {
			logger.log(Level.SEVERE, "Error in transfer to json object.");
		}
		return null;
	}

	@Override
	public void construct(JSONObject json) {
		try {
			super.construct(json);

			if (json.has(S_X))
				addAttribute(S_X, String.valueOf(json.getInt(S_X)));

			if (json.has(S_Y))
				addAttribute(S_Y, String.valueOf(json.getInt(S_Y)));

			if (json.has(S_WIDTH))
				addAttribute(S_WIDTH, String.valueOf(json.getInt(S_WIDTH)));

			if (json.has(S_HEIGHT))
				addAttribute(S_HEIGHT, String.valueOf(json.getInt(S_HEIGHT)));

			if (json.has(S_IMG_SRC))
				addAttribute(S_IMG_SRC, json.getString(S_IMG_SRC));

			if (json.has(S_IMG_ID))
				addAttribute(S_IMG_ID, json.getString(S_IMG_ID));

		} catch (JSONException e) {
			logger.log(Level.SEVERE, "Error in transfer from json object.");
		}
	}

}
